package org.jeecg.modules.product.risk.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.product.risk.entity.TbBaseCheck;
import org.jeecg.modules.product.risk.entity.TbBaseCheckItem;
import org.jeecg.modules.product.risk.service.ITbBaseCheckItemService;
import org.jeecg.modules.product.risk.service.ITbBaseCheckService;
import org.jeecg.modules.product.risk.vo.TbBaseCheckPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 检查表
 * @Author: jeecg-boot
 * @Date:   2024-05-21
 * @Version: V1.0
 */
@Tag(name="检查表")
@RestController
@RequestMapping("/TbBaseCheck/tbBaseCheck")
@Slf4j
public class TbBaseCheckController {
	@Autowired
	private ITbBaseCheckService tbBaseCheckService;
	@Autowired
	private ITbBaseCheckItemService tbBaseCheckItemService;

	/**
	 * 分页列表查询
	 *
	 * @param tbBaseCheck
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "检查表-分页列表查询")
	@Operation(summary="检查表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TbBaseCheck tbBaseCheck,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TbBaseCheck> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseCheck, req.getParameterMap());
		Page<TbBaseCheck> page = new Page<TbBaseCheck>(pageNo, pageSize);
		queryWrapper.eq("deleted", "0");
		IPage<TbBaseCheck> pageList = tbBaseCheckService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tbBaseCheckPage
	 * @return
	 */
	@AutoLog(value = "检查表-添加")
	@Operation(summary="检查表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TbBaseCheckPage tbBaseCheckPage) {
		TbBaseCheck tbBaseCheck = new TbBaseCheck();
		BeanUtils.copyProperties(tbBaseCheckPage, tbBaseCheck);
		tbBaseCheckService.saveMain(tbBaseCheck, tbBaseCheckPage.getTbBaseCheckItemList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tbBaseCheckPage
	 * @return
	 */
	@AutoLog(value = "检查表-编辑")
	@Operation(summary="检查表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TbBaseCheckPage tbBaseCheckPage) {
		TbBaseCheck tbBaseCheck = new TbBaseCheck();
		BeanUtils.copyProperties(tbBaseCheckPage, tbBaseCheck);
		TbBaseCheck tbBaseCheckEntity = tbBaseCheckService.getById(tbBaseCheck.getId());
		if(tbBaseCheckEntity==null) {
			return Result.error("未找到对应数据");
		}
		tbBaseCheckService.updateMain(tbBaseCheck, tbBaseCheckPage.getTbBaseCheckItemList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检查表-通过id删除")
	@Operation(summary="检查表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		tbBaseCheckService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "检查表-批量删除")
	@Operation(summary="检查表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseCheckService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	 /**
	  *   通过id逻辑删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "检查任务企业-通过id逻辑删除")
	 @Operation(summary="检查任务企业-通过id逻辑删除")
	 @DeleteMapping(value = "/logicDelete")
	 public Result<?> logicDelete(@RequestParam(name="id",required=true) String id) {
		 TbBaseCheck tbBaseCheck = tbBaseCheckService.getById(id);
		 tbBaseCheck.setDeleted("1");//禁止状态1是已删除，0是正常未删除
		 tbBaseCheckService.updateById(tbBaseCheck);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量逻辑删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "检查任务企业-批量逻辑删除")
	 @Operation(summary="检查任务企业-批量逻辑删除")
	 @DeleteMapping(value = "/deleteLogicBatch")
	 public Result<?> deleteLogicBatch(@RequestParam(name="ids",required=true) String ids) {
		 List<TbBaseCheck> list = tbBaseCheckService.listByIds(Arrays.asList(ids.split(",")));
		 for (TbBaseCheck tbBaseCheck : list) {
			 tbBaseCheck.setDeleted("1");//禁止状态1是已删除，0是正常未删除
		 }
		 tbBaseCheckService.updateBatchById(list);
		 return Result.OK("批量删除成功！");
	 }

	 /**
	  * 获取被逻辑删除的检查任务企业
	  *
	  * @return logicDeletedUserList
	  */
	 @GetMapping("/recycleBin")
	 public Result getRecycleBin(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 QueryWrapper<TbBaseCheck> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("deleted", "1");//查询已经删除的数据
		 Page<TbBaseCheck> page = new Page<TbBaseCheck>(pageNo, pageSize);
		 IPage<TbBaseCheck> pageList = tbBaseCheckService.page(page, queryWrapper);
		 return Result.ok(pageList);
	 }

	 /**
	  * 还原被逻辑删除的检查任务企业
	  *
	  * @param jsonObject
	  * @return
	  */
	 @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
	 public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
		 String tbBaseCheckIds = jsonObject.getString("tbBaseCheckIds");
		 if (StringUtils.isNotBlank(tbBaseCheckIds)) {
			 List<TbBaseCheck> list = tbBaseCheckService.listByIds(Arrays.asList(tbBaseCheckIds.split(",")));
			 for (TbBaseCheck entity : list) {
				 entity.setDeleted("0");
			 }
			 tbBaseCheckService.updateBatchById(list);
		 }
		 return Result.ok("还原成功");
	 }
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检查表-通过id查询")
	@Operation(summary="检查表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		TbBaseCheck tbBaseCheck = tbBaseCheckService.getById(id);
		if(tbBaseCheck==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tbBaseCheck);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检查项通过主表ID查询")
	@Operation(summary="检查项主表ID查询")
	@GetMapping(value = "/queryTbBaseCheckItemByMainId")
	public Result<?> queryTbBaseCheckItemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TbBaseCheckItem> tbBaseCheckItemList = tbBaseCheckItemService.selectByMainId(id);
		return Result.OK(tbBaseCheckItemList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tbBaseCheck
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TbBaseCheck tbBaseCheck) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<TbBaseCheck> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseCheck, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<TbBaseCheck> queryList = tbBaseCheckService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<TbBaseCheck> tbBaseCheckList = new ArrayList<TbBaseCheck>();
      if(oConvertUtils.isEmpty(selections)) {
          tbBaseCheckList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          tbBaseCheckList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<TbBaseCheckPage> pageList = new ArrayList<TbBaseCheckPage>();
      for (TbBaseCheck main : tbBaseCheckList) {
          TbBaseCheckPage vo = new TbBaseCheckPage();
          BeanUtils.copyProperties(main, vo);
          List<TbBaseCheckItem> tbBaseCheckItemList = tbBaseCheckItemService.selectByMainId(main.getId());
          vo.setTbBaseCheckItemList(tbBaseCheckItemList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "检查表列表");
      mv.addObject(NormalExcelConstants.CLASS, TbBaseCheckPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("检查表数据", "导出人:"+sysUser.getRealname(), "检查表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<TbBaseCheckPage> list = ExcelImportUtil.importExcel(file.getInputStream(), TbBaseCheckPage.class, params);
              for (TbBaseCheckPage page : list) {
                  TbBaseCheck po = new TbBaseCheck();
                  BeanUtils.copyProperties(page, po);
                  tbBaseCheckService.saveMain(po, page.getTbBaseCheckItemList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
